package com.cw.demo.binarysearch.basic;

/**
 * 二分查找法
 *
 * @author chenw
 * @date 2021/1/14
 */
public class BasicBinarySearch {
    /**
     * 基本的二分搜索法
     * 
     * @param sum
     * @param target
     * @return
     */
    public int binarySearch(int[] sum, int target) {
        int left = 0;
        int right = sum.length - 1;
        while (left <= right) {
            int mid = (right + left) / 2;
            if (sum[mid] == target) {
                return mid;
            } else if (sum[mid] < target) {
                left = mid + 1;
            } else if (sum[mid] > target) {
                right = mid - 1;
            }
        }
        return -1;
    }
}
